/*
 * Copyright (c) 2015 smarthome.com All rights reserved. 本软件源代码版权归----所有,未经许可不得任意复制与传播.
 */
package com.smarthome.base.service.base;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smarthome.common.exception.AppException;
import com.smarthome.base.dao.base.BaseDao;
import com.smarthome.domain.common.Page;

/**
 * service实现类
 * @author KongXiangyu
 * @since 2015-08-05
 * @param <T> 实体
 * @param <KEY> 主键
 */
public abstract class BaseServiceImpl<T, KEY extends Serializable> implements BaseService<T, KEY> {

    protected static Logger LOGGER;

    /** 获取DAO操作类 */
    public abstract BaseDao<T, KEY> getDao();

    public String getNameSpace(String statement) {
        return null;
    }

    public BaseServiceImpl() {
        LOGGER = LoggerFactory.getLogger(this.getClass());
    }

    @SuppressWarnings("unchecked")
    public int insert(T... t) {
        return getDao().insertEntry(t);
    }

    @SuppressWarnings("unchecked")
    public int deleteByIds(KEY... ids) {
        return getDao().deleteByKey(ids);
    }

    public int deleteByCondtion(T condtion) {
        return getDao().deleteByKey(condtion);
    }

    public int updateById(T condtion) {
        return getDao().updateByKey(condtion);
    }

    @SuppressWarnings("unchecked")
    public int saveOrUpdate(T t) {
        Long id = 0L;
        try {
            Class<?> clz = t.getClass();
            id = (Long) clz.getMethod("getId").invoke(t);
        } catch (Exception e) {
            LOGGER.warn("获取对象主键值失败!");
        }
        if (id != null && id > 0) {
            return getDao().updateByKey(t);
        }
        return getDao().insertEntry(t);
    }

    public T selectEntryById(KEY id) {
        return getDao().selectEntry(id);
    }

    public List<T> selectEntryListByIds(KEY... ids) {
        return getDao().selectEntryList(ids);
    }

    public List<T> selectEntryList(T condtion) {
        return getDao().selectEntryList(condtion);
    }

    public Page<T> selectPage(T condtion, Page<T> page) {
        try {
            Class<?> clz = condtion.getClass();
            clz.getMethod("setStartIndex", Integer.class).invoke(condtion, page.getStartIndex());
            clz.getMethod("setEndIndex", Integer.class).invoke(condtion, page.getEndIndex());
        } catch (Exception e) {
            throw new AppException("设置分页参数失败", e);
        }
        Integer size = getDao().selectEntryListCount(condtion);
        if (size == null || size <= 0) {
            return page;
        }
        page.setTotalCount(size);
        page.setResult(this.selectEntryList(condtion));
        return page;
    }
}
